const Profile=require("../../model/profile");
const express=require("express");
const passport=require("passport");
const router=express.Router();

// route  /api/profile/test
// @desc 返回请求的json数据
//@access  public
router.get("/test",(req,res)=>{
    res.json({
        msg:"success"
    });
});
// route  /api/profile/add
// @desc 添加信息
//@access  private
router.post("/add",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let profiles={};
    if(req.body.type) profiles.type=req.body.type;
    if(req.body.describe) profiles.describe=req.body.describe;
    if(req.body.income) profiles.income=req.body.income;
    if(req.body.expend) profiles.expend=req.body.expend;
    if(req.body.cash) profiles.cash=req.body.cash;
    if(req.body.remarks) profiles.remarks=req.body.remarks;
    
    new Profile(profiles).save().then((profiles)=>{
        if(profiles){
            return res.json(profiles);
        }
        return res.json({msg:"failure"});
    })
});
// route  /api/profile/
// @desc 获取所有的信息
//@access  private
router.get("/",passport.authenticate("jwt",{session:false}),(req,res)=>{
    Profile.find().then((profiles)=>{
        if(profiles){
            return res.status(200).json(profiles);
        }
        return res.status(404).json("没有任何内容");
    });
});
// route  /api/profile/:id
// @desc 获取单个的信息
//@access  private
router.get("/:id",passport.authenticate("jwt",{session:false}),(req,res)=>{
    Profile.findOne({_id:req.params.id}).then((profiles)=>{
        if(profiles){
            return res.status(200).json(profiles);
        }
        return res.status(404).json("没有任何内容");
    });
});
// route  /api/profile/edit:id
// @desc 编辑单个的信息
//@access  private
router.post("/edit/:id",passport.authenticate("jwt",{session:false}),(req,res)=>{
    let profiles={};
    if(req.body.type) profiles.type=req.body.type;
    if(req.body.describe) profiles.describe=req.body.describe;
    if(req.body.income) profiles.income=req.body.income;
    if(req.body.expend) profiles.expend=req.body.expend;
    if(req.body.cash) profiles.cash=req.body.cash;
    if(req.body.remarks) profiles.remarks=req.body.remarks;
    Profile.findOneAndUpdate(
        {_id:req.params.id},
        {$set:profiles},
        {new:true}
    ).then((profile)=>{
        res.status(200).json(profile);
    })
})
// route  /api/profile/delete/:id
// @desc 删除单个的信息
//@access  private
router.delete("/delete/:id",passport.authenticate("jwt",{session:false}),(req,res)=>{
    Profile.findOneAndRemove({
        _id:req.params.id
    }).then((profiles)=>{
        profiles.save().then(profiles=>{
            res.status(200).json({
                profiles
            });
        })
    }).catch(err=>{
        res.status(200).json("删除失败");
    })
});
module.exports=router;